#!/bin/sh

App=avicit.bdp.dds.ApiApplicationServer

PWD=`pwd`
RESOURCE_NAME=`find ./ -name bdp-*.jar`
RESOURCE_NAME=$PWD/$RESOURCE_NAME
profile=""
if [ -n "$1" ];then
  profile="-Dspring.profiles.active=$1"
fi
echo $profile  $RESOURCE_NAME

cnt=`ps -ef|grep $App|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'| wc -l`
if (( $cnt > 1 )); then
  echo "Error! Too many $App runs, count:$cnt"
  exit
fi

tpid=`ps -ef|grep $App|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
  echo 'stop process...'
  kill -15 $tpid
fi
sleep 5

tpid=`ps -ef|grep $App|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
if [ ${tpid} ]; then
  echo 'kill process!'
  kill -9 $tpid
  tpid=`ps -ef|grep $App|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
      echo 'stop fail! $App is already running.'
  else
      echo 'stop success! $App is NOT running.'
  fi
else
  echo 'stop success!'
fi

rm -f tpid
nohup java -Dloader.main=$App -jar -Dspring.config.location=./application.yml  $profile $RESOURCE_NAME >/dev/null 2>&1 &
echo $! > tpid

cnt=`ps -ef|grep $App|grep $RESOURCE_NAME|grep -v grep|grep -v kill|awk '{print $2}'| wc -l`
if (( $cnt != 1 )); then
  echo "$App start fail!"
else
  echo "$App start success!"
fi

